package com.study.kafkademo.kafka.defalut;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

@Component
@Slf4j
public class DefaultKafkaProducer {
    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    //自定义 主题 topic
    public static final String TOPIC_TEST = "topic.test";

    public static final String TOPIC_GROUP1 = "topic.group1";

    public static final String TOPIC_GROUP2 = "topic.group2";

    public void send(Object obj) {
        final String s = JSONObject.toJSONString(obj);
        log.info("准备发送的消息为：{}", s);
        final ListenableFuture<SendResult<String, Object>> send = kafkaTemplate.send(TOPIC_TEST, obj);
        send.addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
            @Override
            public void onFailure(Throwable ex) {
                //发送消息失败
                log.error(TOPIC_TEST + "-生成者 发送消息失败：" + ex.getMessage());
            }

            @Override
            public void onSuccess(SendResult<String, Object> result) {
                //发送消息成功
                log.info(TOPIC_TEST + "-生成者 发送消息成功：" + JSONObject.toJSONString(result));
            }
        });
    }
}
